<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace common\services\system;

use api\utils\tools\PageUtils;
use api\utils\tools\QueryUtils;
use common\extend\exception\B5HttpException;
use common\models\system\Admin;
use common\models\system\AdminRole;
use Yii;
use yii\db\Exception;

class RoleUserService
{
    /**
     * 获取某个角色的用户列表（分页）
     * @param $roleId
     * @param $params
     * @return array
     */
    public static function selectAuthUsersPage($roleId, $params): array
    {
        $pages = new PageUtils('pageNum', 'pageSize');
        $list = [];
        $count = 0;
        if (!$roleId) return $pages->listFormat($list, $count);
        $query = AdminRole::find()->alias('ar')->select(['a.*'])->leftJoin(Admin::tableName() . ' as a', 'ar.admin_id = a.id')->where(['ar.role_id' => $roleId]);
        try {
            $queryUtils = new QueryUtils($query, $params, 'a');
            $queryUtils->whereParse()->orderParse();

            $query = $queryUtils->getQuery();
            $count = (clone $query)->count();
            $list = $query->offset($pages->getOffset())->limit($pages->getPageSize())->asArray()->all();
        } catch (B5HttpException $exception) {
        }
        return $pages->listFormat($list, $count);
    }

    /**
     * 获取某个角色的未授权用户列表
     * @param $roleId
     * @param $params
     * @return array
     */
    public static function selectUnAllocatedListPage($roleId, $params): array
    {
        $pages = new PageUtils('pageNum', 'pageSize');
        $list = [];
        $count = 0;
        if (!$roleId) return $pages->listFormat($list, $count);

        $adminIdList = self::selectRoleAdminIds($roleId);
        $adminIdList[] = Yii::$app->params['root_admin_id'];
        $query = Admin::find()->where(['not in', 'id', $adminIdList]);
        try {
            $queryUtils = new QueryUtils($query, $params);
            $queryUtils->whereParse()->orderParse();
            $query = $queryUtils->getQuery();
            $count = (clone $query)->count();
            $pages = new PageUtils('pageNum', 'pageSize');
            $list = $query->offset($pages->getOffset())->limit($pages->getPageSize())->asArray()->all();
        } catch (B5HttpException $exception) {
        }
        return $pages->listFormat($list, $count);
    }

    /**
     * 获取某个角色的人员列表
     * @param $roleId
     * @return array
     */
    public static function selectRoleAdminIds($roleId): array
    {
        if (!$roleId) return [];
        $list = AdminRole::find()->where(['role_id' => $roleId])->asArray()->all();
        return $list ? array_column($list, 'admin_id') : [];
    }

    /**
     * 更新角色的用户
     * @param $roleId
     * @param $adminIds
     * @return bool
     */
    public static function addRoleAllocatedAdmin($roleId, $adminIds): bool
    {
        if (!$roleId) return false;
        $adminIds = $adminIds ? array_unique(is_array($adminIds) ? $adminIds : explode(',', $adminIds)) : [];
        if (!$adminIds) return true;
        $data = [];
        foreach ($adminIds as $adminId) {
            if (!$adminId) continue;
            $info = AdminRole::findOne(['admin_id' => $adminId, 'role_id' => $roleId]);
            if (!$info) {
                $data[] = [$adminId, $roleId];
            }
        }
        if (!$data) return true;
        try {
            Yii::$app->db->createCommand()->batchInsert(AdminRole::tableName(), ['admin_id', 'role_id'], $data)->execute();
            return true;
        } catch (Exception $exception) {
            return false;
        }
    }

    /**
     * 删除某条关联
     * @param $roleId
     * @param $adminIds
     */
    public static function deleteRoleUser($roleId, $adminIds)
    {
        if (!$roleId || $adminIds < 1) return;
        $adminIds = array_unique(is_array($adminIds) ? $adminIds : explode(',', $adminIds));
        AdminRole::deleteAll(['role_id' => $roleId, 'admin_id' => $adminIds]);
    }
}
